import 'package:get/get.dart';
import 'package:kkhousekeep/net/home_repair_connect.dart';
import 'package:kkhousekeep/net/respnse_code.dart';
import 'package:kkhousekeep/page/home/convenient/repair/repair_add_controller.dart';
import 'package:kkhousekeep/page/home/convenient/repair/repair_home_controller.dart';
import 'package:kkhousekeep/tools/dialog_util.dart';
import 'package:kkhousekeep/tools/get_dialog_ext.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../../config/constant.dart';
import '../../../../models/repair_order_detail_entity.dart';
import '../../../public/take_picture_screen.dart';

class RepairDetailsController extends GetxController {
  var progressState = ProgressState.completed.obs;

  var orderTime = ''.obs;

  var worker = ''.obs;

  ///报修类型
  var repairType = ''.obs;

  var address = ''.obs;

  var repairApplicant = ''.obs;

  var phone = ''.obs;

  var urgency = ''.obs;

  var fatalType = ''.obs;

  var faultDesc = ''.obs;

  var pics = <String>[].obs;

  var acceptorPhone = "".obs;

  late HomeRepairConnect connect;

  var orderId = -1;

  @override
  void onInit() {
    orderId = Get.arguments[ArgumentKey.orderId] ?? orderId;
    connect = Get.find<HomeRepairConnect>();
    _loadNetworkData();
    super.onInit();
  }

  void performClickButton() {
    if (progressState.value == ProgressState.completed) {
      return;
    }

    if (progressState.value == ProgressState.pending) {
      Get.showCupertinoDialog(
        content: '是否取消该维修申请',
        onRightTap: performClickCancelApply,
      );
      return;
    }

    if (progressState.value == ProgressState.processing) {
      ///进入拨打电话页面
      launchUrl(Uri.parse('tel:${acceptorPhone.value}'));
    }
  }

  void performClickCancelApply() async {
    var response = await connect.cancelApply(orderId: orderId);
    if (response == null) {
      return;
    }
    if (response.code == ResponseCode.success) {
      Get.back();
      return;
    }
    DialogUtil.showNetworkFail();
  }

  void performClickImageItem(String path) {
    Get.to(DisplayPictureScreen(
      imagePath: path,
      isShowRetake: false,
    ));
  }

  void _loadNetworkData() async {
    RepairOrderDetailObj entity =
        await connect.getRepairOrderDetail(orderId: orderId);

    orderTime.value = entity.time;
    worker.value = entity.worker;
    repairType.value = RepairAreaType.getNameById(entity.repairArea);
    address.value = entity.address;
    repairApplicant.value = entity.repairApplicant;
    phone.value = entity.phone;
    urgency.value = UrgencyType.getNameById(entity.urgency);
    fatalType.value = entity.fatalType;
    faultDesc.value = entity.fatalMark;
    pics.value = entity.pics;
    progressState.value = ProgressState.getProgressStateByState(entity.state);
    acceptorPhone.value = entity.acceptorPhone;
  }
}
